/*
 * @Descripttion: GGB
 * @version: 1.0
 * @Author: GGB
 * @Date: 2021-07-29 16:00:26
 * @LastEditors: GGB
 * @LastEditTime: 2021-07-29 16:23:33
 */
import 'package:flutter/material.dart';
import 'package:flutter_faster_study/apps/QR/screens/components/button_widget.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key key}) : super(key: key);

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final keyText = GlobalKey();
  Size size;
  Offset position;
  // 该方法保证了在（build函数渲染完之后）页面渲染完成之后执行
  void calculateSizeAndPosition() =>
      WidgetsBinding.instance.addPostFrameCallback((_) {
        final RenderBox box =
            keyText.currentContext.findRenderObject(); // 包含widget的绘制信息
        setState(() {
          position = box.localToGlobal(Offset.zero); // 获取绝对信息 从左上角
          size = box.size;
        });
      });
  @override
  void initState() {
    super.initState();
    calculateSizeAndPosition();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          buildText(),
          SizedBox(height: 32),
          ButtonWidget(
            text: "获取小部件信息",
            onClicked: () {
              calculateSizeAndPosition();
            },
          ),
          SizedBox(height: 30),
          buildResult(),
        ],
      ),
    );
  }

  buildText() => Text(
        "这是一窜文本啦",
        key: keyText,
        style: TextStyle(
          fontSize: 40,
          fontWeight: FontWeight.bold,
        ),
      );

  buildResult() {
    if (size == null || position == null) return Container();
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('宽度：${size.width.toInt()}'),
        Text('高度：${size.height.toInt()}'),
        Text('x坐标：${position.dx.toInt()}'),
        Text('y坐标：${position.dy.toInt()}'),
      ],
    );
  }
}
